package com.ruoyi.fin.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.api.event.EventListener;
import com.ruoyi.api.event.EventType;
import com.ruoyi.api.event.TransactionEvent;
import com.ruoyi.fin.domain.FinAccount;
import com.ruoyi.fin.mapper.FinAccountMapper;
import com.ruoyi.fin.service.IFinAccountService;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;

/**
 * 交易记录余额更新监听器
 * 当交易记录被添加或删除时，更新相关账户的余额
 */
@Component
public class TransactionBalanceUpdateListener implements EventListener<TransactionEvent> {

    private static final Logger logger = LoggerFactory.getLogger(TransactionBalanceUpdateListener.class);

    @Autowired
    private IFinAccountService finAccountService;
    
    @Autowired
    private com.ruoyi.api.event.EventCenter eventCenter;
    
    @PostConstruct
    public void init() {
        // 注册监听器
        eventCenter.registerListener(this);
        logger.info("Registered TransactionBalanceUpdateListener");
    }

    @Override
    public void onEvent(TransactionEvent event) {
        if (event.getEventType() != EventType.TRANSACTION_ADDED && 
            event.getEventType() != EventType.TRANSACTION_DELETED) {
            return;
        }
        
        Long accountId = event.getAccountId();
        BigDecimal amount = event.getAmount();
        
        logger.info("Processing transaction event: {} for account ID: {}, amount: {}", 
                event.getEventType(), accountId, amount);
        
        // 获取账户信息
        FinAccount account = finAccountService.selectFinAccountById(accountId);
        if (account == null) {
            logger.error("Account not found with ID: {}", accountId);
            return;
        }
        
        // 根据事件类型更新余额
        BigDecimal newBalance;
        if (event.getEventType() == EventType.TRANSACTION_ADDED) {
            // 添加交易记录时，更新余额
            newBalance = account.getBalance().add(amount);
        } else {
            // 删除交易记录时，反向更新余额
            newBalance = account.getBalance().subtract(amount);
        }
        
        logger.info("Updating account balance from {} to {}", account.getBalance(), newBalance);
        
        // 更新账户余额
        account.setBalance(newBalance);
        finAccountService.updateFinAccount(account);
    }

    @Override
    public EventType getSupportedEventType() {
        // 这个监听器支持两种事件类型，但实际上在处理时会判断具体类型
        return EventType.TRANSACTION_ADDED;
    }
    
    @Override
    public Class<TransactionEvent> getSupportedEventClass() {
        return TransactionEvent.class;
    }
} 